/**
 * Global authority directive
 * Used for fine-grained control of component permissions
 * @Example v-auth="['admin', 'user:edit', 'user:del']"
 */
import type { App, Directive, DirectiveBinding } from 'vue';
import { useUserStore } from '../store/modules/user';

const userStore = useUserStore();
/**
 * Determine whether there is permission
 */
function hasPermission(value?: string[], def = false): boolean {
  if (value && value instanceof Array && value.length > 0) {
    const roles = userStore.getRoles ?? [];
    const permissionRoles = value;
    return roles.some((role) => {
      return permissionRoles.includes(role);
    });
  } else {
    console.error('need roles! Like v-auth=[admin,editor]');
    return def;
  }
}

function isAuth(el: Element, binding: any) {
  const value = binding.value;
  if (!value) return;
  if (!hasPermission(value)) {
    el.parentNode?.removeChild(el);
  }
}

const mounted = (el: Element, binding: DirectiveBinding<any>) => {
  isAuth(el, binding);
};

const authDirective: Directive = {
  mounted,
};

export function setupPermissionDirective(app: App) {
  app.directive('auth', authDirective);
}

export default authDirective;
